/**
 * A Selection represents the set of selected Shapes.
 * A Selection is observable by SelectionListeners.
 * 
 * @author Giuseppe Mendola (giuseppe.mendola@usi.ch);Gregory Banfi (gregory.banfi@usi.ch);
 */

package ch.usi.inf.pf2.gui;


import java.util.Iterator;
import java.util.ArrayList;

import ch.usi.inf.pf2.Component;

public final class Selection implements Iterable<Component> {

	private ArrayList<Component> components;
	private ArrayList<SelectionListener> listeners;

	public Selection() {
		components = new ArrayList<Component>();
		listeners = new ArrayList<SelectionListener>();
	}

	/**
	 * This method clears the selection HashSet<Component>.
	 */
	public void clear() {
		components.clear();
		//System.out.println("Selection.clear()");
		fireSelectionChanged();
	}

	/**
	 * This method returns the size of the HashSet<Component>.
	 */
	public int getSize() {
		return components.size();
	}

	/**
	 * This method adds a component to the selection HashSet<Component>.
	 */
	public void add(final Component component) {
		components.add(component);
		fireSelectionChanged();
	}

	/**
	 * This method removes a component to the selection HashSet<Component>.
	 */
	public void remove(final Component component) {
		components.remove(component);
		fireSelectionChanged();
	}

	/**
	 * This method returns an iterator for the selection HashSet<Component>.
	 */
	@Override
	public Iterator<Component> iterator() {
		return components.iterator();
	}

	// --- listener management
	public void addSelectionListener(final SelectionListener li) {
		listeners.add(li);
	}

	/**
	 * This method advises all the listeners that the selection is changed.
	 */
	private void fireSelectionChanged() {
		for (final SelectionListener li : listeners) {
			li.selectionChanged();
		}
	}

}
